import { DataTypes } from 'sequelize';
import { sequelize } from '../config/database.js';

const UserQuota = sequelize.define('UserQuota', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  user_id: {
    type: DataTypes.INTEGER,
    allowNull: false,
    comment: '用户ID'
  },
  quota_type: {
    type: DataTypes.ENUM('general', 'domain', 'expert'),
    allowNull: false,
    comment: '额度类型：general-通用，domain-领域，expert-专家'
  },
  target_id: {
    type: DataTypes.INTEGER,
    allowNull: true,
    comment: '目标ID（领域ID或专家ID）'
  },
  total_count: {
    type: DataTypes.INTEGER,
    allowNull: false,
    defaultValue: 0,
    comment: '总次数'
  },
  used_count: {
    type: DataTypes.INTEGER,
    allowNull: false,
    defaultValue: 0,
    comment: '已使用次数'
  },
  remaining_count: {
    type: DataTypes.INTEGER,
    allowNull: false,
    defaultValue: 0,
    comment: '剩余次数'
  },
  expires_at: {
    type: DataTypes.DATE,
    allowNull: true,
    comment: '过期时间'
  },
  created_at: {
    type: DataTypes.DATE,
    defaultValue: DataTypes.NOW
  },
  updated_at: {
    type: DataTypes.DATE,
    defaultValue: DataTypes.NOW
  }
}, {
  tableName: 'user_quotas',
  timestamps: true,
  createdAt: 'created_at',
  updatedAt: 'updated_at',
  indexes: [
    {
      name: 'idx_user_quotas_user_id',
      fields: ['user_id'],
    },
    {
      name: 'idx_user_quotas_quota_type',
      fields: ['quota_type'],
    },
    {
      name: 'idx_user_quotas_target_id',
      fields: ['target_id'],
    },
    {
      name: 'idx_user_quotas_expires_at',
      fields: ['expires_at'],
    },
    {
      name: 'idx_user_quotas_remaining_count',
      fields: ['remaining_count'],
    },
  ],
  hooks: {
    beforeSave: (quota) => {
      // 自动计算剩余次数
      quota.remaining_count = quota.total_count - quota.used_count;
    }
  }
});

// 实例方法
UserQuota.prototype.toJSON = function() {
  const values = { ...this.get() };
  return values;
};

UserQuota.prototype.canUse = function() {
  if (this.remaining_count <= 0) return false;
  if (this.expires_at && new Date() > this.expires_at) return false;
  return true;
};

UserQuota.prototype.useQuota = async function() {
  if (!this.canUse()) {
    throw new Error('额度不足或已过期');
  }
  
  this.used_count += 1;
  this.remaining_count = this.total_count - this.used_count;
  await this.save();
  return this;
};

UserQuota.prototype.addQuota = async function(count) {
  this.total_count += count;
  this.remaining_count = this.total_count - this.used_count;
  await this.save();
  return this;
};

// 类方法
UserQuota.findAvailableQuota = function(userId, quotaType, targetId = null) {
  const where = {
    user_id: userId,
    quota_type: quotaType,
    remaining_count: { [sequelize.Sequelize.Op.gt]: 0 }
  };
  
  if (targetId) {
    where.target_id = targetId;
  }
  
  return this.findOne({
    where,
    order: [['expires_at', 'ASC']] // 优先使用即将过期的额度
  });
};

UserQuota.getUserQuotas = function(userId) {
  return this.findAll({
    where: { user_id: userId },
    include: [
      { association: 'domain', attributes: ['id', 'name'] },
      { association: 'expert', attributes: ['id', 'nickname'] }
    ],
    order: [['created_at', 'DESC']]
  });
};

UserQuota.createQuota = async function(quotaData) {
  const quota = await this.create(quotaData);
  return quota;
};

export default UserQuota;
